package com.tms.firtsp.service;

import com.tms.firtsp.common.REnum;
import com.tms.firtsp.common.RException;
import com.tms.firtsp.entities.Student;
import com.tms.firtsp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    public List<Student> findAll(){
      return   studentRepository.findAllByOrderByIdDesc();
    }

    /**
     * 按名字查找
     * @param name 名字
     * @return
     */
    public List<Student> findByName(String name){
        return   studentRepository.findByName(name);
    }


    /**
     * 按名字和密码查找
     * @param name 名字
     * @param password 密码
     * @return
     */
    public List<Student> findByNameAndPassword(String name,String password){
        return   studentRepository.findByNameAndPassword(name,password);
    }

    /**
     * 按名字查找
     * @param name 名字
     * @return
     */
    public List<Student> findByNameLike(String name){
        return   studentRepository.findByNameLike(name);
    }


    /**
     * 保存学生
     * @param student
     * @return
     */
    @Transactional
    public Student save(Student student){
     return   studentRepository.save(student);
    }


    /**
     * 保存学生
     * @param student
     * @return
     */
    @Transactional
    public Student update(Student student){
        return   studentRepository.save(student);
    }

    public  Student findOne(Integer id){
        return studentRepository.findOne(id);
    }

    public void delete(Integer id){
        studentRepository.delete(id);
    }

    public void delete(Integer[] ids){
        //读取多个ids
        //循环删除它
        Integer len=ids.length;
        for (Integer i=0;i<len;i++){
            Student student=studentRepository.getOne(ids[i]);
            studentRepository.delete(student);
        }



    }


    public Boolean validUserNameAndPassword(String userName,String password) throws  Exception{
        if(userName.equals("admin") && password.equals("1111")){

        }else{
            throw  new RException(REnum.LOGIN_ERR);
        }
        return true;
    }

}
